<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="searchForm" :inline="true">
            <el-form-item label="分类">
              <el-select v-model="searchForm.parentId" placeholder="请选择分类" clearable>
                <el-option v-for="item in template_catalogue" :key="item.id" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="模板名称">
              <el-input v-model="searchForm.realName" placeholder="请输入模板名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="文档类型">
              <el-select v-model="searchForm.type" placeholder="请选择文档类型" clearable>
                <el-option label="word" value="word"></el-option>
                <el-option label="excel" value="excel"></el-option>
                <el-option label="ppt" value="ppt"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" plain :icon="Plus" @click="deleteItemAll">删除全部模板</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain :icon="Plus" @click="handleAdd">新建模板</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain :icon="Plus" @click="handleAddPl">批量上传</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getTableData(`reset`)"></right-toolbar>
        </el-row>
      </template>

      <el-table ref="roleTableRef" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
        <el-table-column label="模版名称">
          <template #default="scope">
            <span style="margin-left: 10px">{{ scope.row.realName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="collection" label="收藏量"> </el-table-column>
        <el-table-column prop="download" label="使用量"> </el-table-column>
        <el-table-column prop="parentId" label="分类">
          <!-- <template slot-scope="scope">
              <span>{{ fenlei(scope.row.parentId) }}</span>
            </template> -->
        </el-table-column>
        <el-table-column prop="thumbnailBase64" label="封面">
          <template #default="scope">
            <span v-if="!scope.row.thumbnailBase64">暂无封面</span>
            <el-image
              v-else
              style="width: 50px; height: 50px"
              :src="scope.row.thumbnailBase64"
              :preview-src-list="[scope.row.thumbnailBase64]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="fileName" label="原文件"> </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" :icon="Edit" @click="onModify(scope.row)"> </el-button>
            <el-button size="small" :icon="Delete" type="danger" @click="handleDelete(scope.row)"> </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="common.total > 0" v-model:page="common.page" v-model:limit="common.size" :total="common.total" @pagination="getTableData" />
    </el-card>
    <!-- 新建模板 -->
    <el-dialog v-model="addTemplateShow" :title="dialogTitle" width="500" :before-close="onClose1">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="模版名称" :label-width="formLabelWidth" prop="realName">
          <el-input v-model="form.realName" autocomplete="off" placeholder="请输入模版名称"></el-input>
        </el-form-item>
        <el-form-item label="模版分类" :label-width="formLabelWidth" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择">
            <el-option v-for="item in template_catalogue" :key="item.id" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择部门" :label-width="formLabelWidth">
          <el-tag v-for="(item, index) in dialogDeptList" :key="index" style="margin-right: 5px">{{ item.deptName }}</el-tag>
          <el-button type="primary" @click="OpenYuSelectDeptClick">选择部门</el-button>
        </el-form-item>
        <el-form-item label="封面" :label-width="formLabelWidth">
          <UploadImg :limit="1" ref="UploadImgRef" />
        </el-form-item>
        <el-form-item label="文件" :label-width="formLabelWidth" :required="isAdd">
          <UploadFile :limit="1" ref="UploadFileRef" describe="只能上传word/excel/ppt文件，且不超过10M" accept=".ppt,.pptx,.doc,.docx,.xls,.xlsx" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="onClose1">取消</el-button>
          <el-button type="primary" @click="saveEdit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 批量上传 -->
    <el-dialog v-model="batchAddTemplateShow" title="新建模板" width="500" :before-close="onClose2">
      <el-form :model="form1" :rules="rules1" ref="ruleForm1">
        <el-form-item label="模版分类" :label-width="formLabelWidth" prop="parentId">
          <el-select v-model="form1.parentId" placeholder="请选择">
            <el-option v-for="item in template_catalogue" :key="item.id" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择部门" :label-width="formLabelWidth">
          <el-tag v-for="(item, index) in dialogDeptList" :key="index" style="margin-right: 5px">{{ item.deptName }}</el-tag>
          <el-button type="primary" @click="OpenYuSelectDeptClick">选择部门</el-button>
        </el-form-item>
        <el-form-item label="文件" :label-width="formLabelWidth" required class="pLUploadFileitem">
          <UploadFile :limit="999" ref="pLUploadFile" :multiple="true" describe="只能上传word/excel/ppt文件，且不超过10M" accept=".ppt,.pptx,.doc,.docx,.xls,.xlsx"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
        <el-button @click="onClose2">取 消</el-button>
        <el-button type="primary" @click="batchEdit">确 定</el-button>
      </div>
      </template>
      
    </el-dialog>
    <YuSelectDept ref="YuSelectDeptRefs" @handleNodeDblClick="handleNodeDblClick"></YuSelectDept>
  </div>
</template>
  
  <script setup lang="ts">
import { Delete, Plus, Edit } from '@element-plus/icons-vue';
import {
  apiadminQueryTemplate,
  apideleteTemplateById,
  apiupdateTemplate,
  apicreateTemplate,
  apibatchUpload,
  deleteAllTemplate
} from '@/api/templateFile/index';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import UploadImg from './component/uploadImg.vue';
import UploadFile from './component/uploadFile.vue';
import YuSelectDept from './component/yu-select-dept.vue';
const { template_catalogue } = toRefs<any>(proxy?.useDict('template_catalogue'));
const router = useRouter();

const loading = ref(false);
const showSearch = ref(true);
const dataList = ref([]);
const selectionList = ref([]);
const searchForm = reactive({
  type: '',
  realName: '',
  parentId: ''
});

const common = reactive({
  page: 1,
  size: 10,
  total: 0
});

const getApplyType = (type) => {
  let item = template_catalogue.value.find((item) => item.value == type);
  if (item) {
    return item.label;
  }
};
/**
 * 查询模板列表
 */
const getTableData = (reset: any) => {
  loading.value = true;
  if (reset == 'reset') {
    common.size = 10;
    common.page = 1;
  }
  let params: any = {
    type: searchForm.type,
    realName: searchForm.realName,
    parentId: searchForm.parentId,
    size: common.size,
    page: common.page - 1
  };
  apiadminQueryTemplate(params).then((res: any) => {
    dataList.value = res.data.rows;
    common.total = res.data.total;
    loading.value = false;
  });
};

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  common.page = 1;
  getTableData('reset');
};

/** 重置 */
const resetQuery = () => {
  searchForm.realName = '';
  searchForm.parentId = '';
  searchForm.type = '';
  handleQuery();
};
const handleSelectionChange = (val) => {
  selectionList.value = val;
};
/**删除按钮操作 */
const handleDelete = async (row) => {
  ElMessageBox.confirm('此操作将永久删除该表单, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let oParam = { id: row.id };
      const res = await apideleteTemplateById(oParam);
      if (res.code == 200) {
        ElMessage.success('删除成功');
        getTableData('');
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
};

const imgSrc = computed(() => {});
// 新建模板
const addTemplateShow = ref<boolean>(false);
// 关闭新增模板弹窗
const handleClose = () => {};
// 打开新建模板弹窗
const handleAdd = () => {
     dialogTitle.value = '新建模板'
  addTemplateShow.value = true;
  isAdd.value = true;
};
const dialogTitle = ref('')
// 新建模板参数
const formLabelWidth = ref<any>('80px');
const form = reactive({
  id: '',
  realName: '',
  parentId: ''
});
const rules = reactive({
  realName: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  parentId: [{ required: true, message: '请选择模板分类', trigger: 'blur' }]
});
const isAdd = ref<boolean>(false);
// 打开选择部门对话框
const YuSelectDeptRefs = ref(null);
const OpenYuSelectDeptClick = () => {
  YuSelectDeptRefs.value.dialogTransfer = true;
};
// 选择部门确定事件
const dialogDeptList = ref([]);
const handleNodeDblClick = (val: any) => {
  dialogDeptList.value = [JSON.parse(JSON.stringify(val))];
};
// 保存新建
const ruleForm = ref(null);
const UploadFileRef = ref(null);
const UploadImgRef = ref(null);
const saveEdit = () => {
  ruleForm.value.validate(async (valid: any) => {
    if (valid) {
      if (!UploadFileRef.value.fileLis.length && isAdd.value) {
        ElMessage.warning('请上传文件');
        return;
      }
      let formData = new FormData();
      formData.append('id', form.id);
      formData.append('realName', form.realName);
      formData.append('parentId', form.parentId);
      if (UploadImgRef.value.fileLis.length) {
        formData.append('image', UploadImgRef.value.fileLis[0].raw);
      }
      if (UploadFileRef.value.fileLis.length) {
        formData.append('file', UploadFileRef.value.fileLis[0].raw);
      }
      let deptId = dialogDeptList.value.map((item: any) => item.deptId);
      formData.append('deptId', deptId.join(','));
      if (form.id) {
        await apiupdateTemplate(formData).then((res: any) => {
          if (res.code == '200') {
            ElMessage.success(res.msg);
            onClose1()
            getTableData('');
          }
        });
      } else {
        await apicreateTemplate(formData).then((res: any) => {
          if (res.code == '200') {
            ElMessage.success(res.msg);
            onClose1()
            getTableData('');
          }
        });
      }
    }
  });
};
// 关闭清除值
const onClose1 = () =>{
    addTemplateShow.value = false;
    form.id = ''
    form.realName = ''
    form.parentId = ''
    isAdd.value = false;
    dialogDeptList.value = [];
    UploadFileRef.value.fileLis = [];
    UploadImgRef.value.fileLis = []
}
// 编辑
const onModify = (row:any) =>{
     dialogTitle.value = '修改模板'
      isAdd.value = false;
      addTemplateShow.value = true;
      form.realName = row.realName
      form.id = row.id;
      form.parentId = `${row.parentId}`;
      if (row.deptId) {
        dialogDeptList.value = [
          {
            deptId: row.deptId,
            deptName: row.deptName
          }
        ];
      }
}
// 批量上传 代码
const batchAddTemplateShow = ref<boolean>(false);
const form1 = reactive({
  parentId: ''
});
const rules1 = reactive({
    parentId: [{ required: true, message: "请选择模板分类", trigger: "blur" }]
})
const handleAddPl = () => {
  batchAddTemplateShow.value = true;
};
const ruleForm1 = ref(null)
const pLUploadFile = ref(null)
const batchEdit = () =>{
    ruleForm1.value.validate( async (valid:any)=>{
        if (valid) {
          if (!pLUploadFile.value.fileLis.length) {
            ElMessage.warning("请上传文件");
            return;
          }
          let formData = new FormData();
          formData.append("parentId", form1.parentId);
          pLUploadFile.value.fileLis.map((item:any) => {
            formData.append("files", item.raw);
          });
          let deptId = dialogDeptList.value.map((item: any) => item.deptId);
          formData.append('deptId', deptId.join(','));
          let res:any = await apibatchUpload(formData);
          if (res.code == "200") {
            ElMessage.success(res.message);
            onClose2();
            getTableData('')
          }
        }
    })
}
// 关闭清除值
const onClose2 = () =>{
    batchAddTemplateShow.value = false;
    form1.parentId = '';
    pLUploadFile.value.fileLis = [];
    dialogDeptList.value = [];
}
// 删除全部模板
const deleteItemAll = () =>{
    ElMessageBox.confirm("此操作将永久删除全部模板目录文件, 是否继续?", "提示", {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res:any = await deleteAllTemplate();
      if (res.code == 200) {
        ElMessage.success('删除成功');
        getTableData('');
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
}
onMounted(() => {
  // getList()
  getTableData('reset');
});
</script>
  <style scoped lang="scss">
#form-template {
  padding: 20px 20px 45px;

  .form-list {
    .el-form {
      display: flex;
      flex-wrap: wrap;

      .search-btn {
        margin-left: 10px;

        :deep(.el-form-item__content) {
          margin-left: 0px !important;
        }
      }
    }

    .el-icon-delete {
      margin: 0px 10px;
    }

    .icon {
      cursor: pointer;
    }

    .el-pagination {
      margin-top: 18px;
    }
  }
}
</style>